import urllib.request
import json
import jsonpath

# 请求部分
url = "https://www.12306.cn/index/otn/index12306/queryAllCacheSaleTime"
headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64)"
                  " AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.88 Safari/537.36"
}
request = urllib.request.Request(url=url, headers=headers)
response = urllib.request.urlopen(request)
data = response.read().decode("utf-8")

# 将数据写入文件
with open("station.json", "w", encoding="utf-8") as fp:
    fp.write(data)

# 读取并解析 JSON 文件
with open("station.json", "r", encoding="utf-8") as file:
    file_data = json.load(file)

    station_name_list = jsonpath.jsonpath(file_data, "$..station_name")
    station_code_list = jsonpath.jsonpath(file_data, "$..station_telecode")

# 确保 station_name_list 和 station_code_list 长度相同
if len(station_name_list) == len(station_code_list):
    for station_name, station_code in zip(station_name_list, station_code_list):
        print(f"{station_name}: {station_code}")
        with open("station_code.txt", "a", encoding="utf-8") as f:
            f.write(f"{station_name}: {station_code}\n")





